package com.ruoyi.app.controller;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.app.domain.*;
import com.ruoyi.app.service.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 校友会活动（无物理外键，通过业务逻辑维护关联）Controller
 *
 * @author 苗瑞春
 * @date 2025-11-04
 */
@RestController
@RequestMapping("/app/activity")
public class AppBase6Controller extends BaseController {
    @Autowired
    private IAppActivitiesService appActivitiesService;

    /**
     * 查询校友会活动（无物理外键，通过业务逻辑维护关联）列表
     */

    @GetMapping("/activity/activitylist")
    public TableDataInfo activitylist(AppActivities appActivities) {
        startPage();
        List<AppActivities> list = appActivitiesService.selectAppActivitiesList(appActivities);
        return getDataTable(list);
    }

    /**
     * 导出校友会活动（无物理外键，通过业务逻辑维护关联）列表
     */

    @Log(title = "校友会活动（无物理外键，通过业务逻辑维护关联）", businessType = BusinessType.EXPORT)
    @PostMapping("/activity/activityexport")
    public void activityexport(HttpServletResponse response, AppActivities appActivities) {
        List<AppActivities> list = appActivitiesService.selectAppActivitiesList(appActivities);
        ExcelUtil<AppActivities> util = new ExcelUtil<AppActivities>(AppActivities.class);
        util.exportExcel(response, list, "校友会活动（无物理外键，通过业务逻辑维护关联）数据");
    }

    /**
     * 获取校友会活动（无物理外键，通过业务逻辑维护关联）详细信息
     */

    @GetMapping(value = "/activity/{activityId}")
    public AjaxResult activitygetInfo(@PathVariable("activityId") Long activityId) {
        return success(appActivitiesService.selectAppActivitiesByActivityId(activityId));
    }

    /**
     * 新增校友会活动（无物理外键，通过业务逻辑维护关联）
     */

    @Log(title = "校友会活动（无物理外键，通过业务逻辑维护关联）", businessType = BusinessType.INSERT)
    @PostMapping("/activity/activityadd")
    public AjaxResult activityadd(@RequestBody AppActivities appActivities) {
        return toAjax(appActivitiesService.insertAppActivities(appActivities));
    }

    /**
     * 修改校友会活动（无物理外键，通过业务逻辑维护关联）
     */

    @Log(title = "校友会活动（无物理外键，通过业务逻辑维护关联）", businessType = BusinessType.UPDATE)
    @PutMapping("/activity/activityedit/{activityId}")
    public AjaxResult activityedit(@RequestBody AppActivities appActivities) {
        return toAjax(appActivitiesService.updateAppActivities(appActivities));
    }

    /**
     * 删除校友会活动（无物理外键，通过业务逻辑维护关联）
     */

    @Log(title = "校友会活动（无物理外键，通过业务逻辑维护关联）", businessType = BusinessType.DELETE)
    @DeleteMapping("/activity/batch/{activityIds}")
    public AjaxResult activityremove(@PathVariable Long[] activityIds) {
        return toAjax(appActivitiesService.deleteAppActivitiesByActivityIds(activityIds));
    }

    @Autowired
    private IAppMediumActivityUserService appMediumActivityUserService;

    /**
     * 查询指定活动的报名人数
     *
     * @param activityId 活动ID
     * @return 报名人数（AjaxResult 封装）
     */
    @GetMapping("/activity/enrollCount/{activityId}")
    public AjaxResult getEnrollCount(@PathVariable Long activityId) {
        int count = appMediumActivityUserService.countEnrolledUsersByActivityId(activityId);
        return AjaxResult.success("查询成功", count);
    }

    /**
     * 用户报名活动
     *
     * @param userId     用户ID
     * @param activityId 活动ID
     * @return 响应结果
     */
    @PostMapping("/activity/enroll")
    public AjaxResult enroll(@RequestParam Long userId, @RequestParam Long activityId) {
        try {
            int result = appMediumActivityUserService.enrollActivity(userId, activityId);
            String msg = (result == 1) ? "报名成功" : "已更新报名状态";
            return AjaxResult.success(msg);
        } catch (IllegalArgumentException e) {
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("报名失败：" + e.getMessage());
        }
    }

    /**
     * 用户收藏活动
     *
     * @param userId     用户ID
     * @param activityId 活动ID
     * @return 响应结果
     */
    @PostMapping("/activity/collect")
    public AjaxResult collect(@RequestParam Long userId, @RequestParam Long activityId) {
        try {
            int result = appMediumActivityUserService.collectActivity(userId, activityId);
            String msg = (result == 1) ? "收藏成功" : "已更新收藏状态";
            return AjaxResult.success(msg);
        } catch (IllegalArgumentException e) {
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("收藏失败：" + e.getMessage());
        }
    }

    @Autowired
    private IAppActivityTagsService appActivityTagsService;

    /**
     * 查询活动自选标签（存储所有可选标签）列表
     */
    @GetMapping("/activity/tag/list")
    public TableDataInfo list(AppActivityTags appActivityTags) {
        startPage();
        List<AppActivityTags> list = appActivityTagsService.selectAppActivityTagsList(appActivityTags);
        return getDataTable(list);
    }

    @Autowired
    private IAppMediumActivityTagService appMediumActivityTagService;

    /**
     * 获取活动与自选标签的关联详细信息
     */

    @GetMapping(value = "/activity/tag/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(appMediumActivityTagService.selectAppMediumActivityTagById(id));
    }

    /**
     * 新增活动与自选标签的关联
     */

    @Log(title = "活动与自选标签的关联", businessType = BusinessType.INSERT)
    @PostMapping("/activity/tag/relation")
    public AjaxResult add(@RequestBody AppMediumActivityTag appMediumActivityTag) {
        return toAjax(appMediumActivityTagService.insertAppMediumActivityTag(appMediumActivityTag));
    }


    @Autowired
    private IAppMediumUsersOrganizationService appMediumUsersOrganizationService;
    @Autowired
    private IAppOrganizationService appOrganizationService;


    /**
     * 根据用户ID查询其加入的所有组织详情（逐个查询组织信息）
     * @param userId 用户ID
     * @return 包含组织详情的列表
     */

    @GetMapping("/activity/user/organizations/detail/{userId}")
    public TableDataInfo getUserOrganizationDetails(@PathVariable Long userId) {
        // 1. 查询该用户关联的所有组织ID（从关联表中获取）
        AppMediumUsersOrganization relationQuery = new AppMediumUsersOrganization();
        relationQuery.setUserId(userId);
        List<AppMediumUsersOrganization> relationList = appMediumUsersOrganizationService
                .selectAppMediumUsersOrganizationList(relationQuery);

        // 2. 若没有关联记录，直接返回空列表
        if (relationList == null || relationList.isEmpty()) {
            return getDataTable(Collections.emptyList());
        }

        // 3. 逐个查询组织详情并封装结果
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (AppMediumUsersOrganization relation : relationList) {
            Long orgId = relation.getOrganizationId(); // 获取组织ID
            if (orgId == null) {
                continue; // 跳过无效的组织ID
            }

            // 调用单条查询方法获取组织详情
            AppOrganization organization = appOrganizationService.selectAppOrganizationByOrganizationId(orgId);
            if (organization != null) {
                // 封装组织详情+关联信息（如加入时间）
                Map<String, Object> orgDetail = new HashMap<>();
                orgDetail.put("organization", organization); // 组织完整信息
                orgDetail.put("joinTime", relation.getJoinTime()); // 加入组织的时间（从关联表获取）
                // 可根据需要添加其他关联字段（如角色、状态等）
                resultList.add(orgDetail);
            }
        }

        return getDataTable(resultList);
    }


    /**
     * 查询一个活动的所有标签名称（最多返回8个）
     * @param activityId 活动ID
     * @return 标签名称列表（仅含tagName，最多8个）
     */
    @GetMapping("/activity/tags/{activityId}")
    public AjaxResult getActivityTags(@PathVariable Long activityId) {
        // 1. 校验活动ID
        if (activityId == null) {
            return AjaxResult.error("活动ID不能为空");
        }

        // 2. 根据活动ID查询所有关联的标签ID
        List<Long> tagIds = appMediumActivityTagService.selectTagIdsByActivityId(activityId);
        if (tagIds == null || tagIds.isEmpty()) {
            return AjaxResult.success("该活动未关联任何标签", Collections.emptyList());
        }

        // 3. 循环查询标签名称，最多返回8个
        List<String> tagNames = new ArrayList<>(8); // 仅存储tagName
        for (Long tagId : tagIds) {
            if (tagNames.size() >= 8) {
                break; // 达到8个则停止
            }
            if (tagId == null) {
                continue; // 跳过无效ID
            }
            // 查询标签详情
            AppActivityTags tag = appActivityTagsService.selectAppActivityTagsByTagId(tagId);
            if (tag != null && tag.getTagName() != null) {
                tagNames.add(tag.getTagName()); // 只添加tagName
            }
        }

        // 4. 返回结果（仅含tagName列表）
        return AjaxResult.success("查询成功", tagNames);
    }





}